<template>
  <div style="height: 100%" class="tree-remote-outer">
    <div class="tree-bar">
      <img :src="rootInfo.avatar_url" style="margin-right: 4px" />
      {{ rootInfo.baidu_name }}
      <!-- {{ formatSize(usedInfo.used) }}G / {{ formatSize(usedInfo.total) }}G -->
      <div style="flex-grow: 1"></div>
      <div v-if="curNode && curNode.nodeType === 'folder'">
        <Button size="small" type="default" @click="pullFolder" title="同步">同步</Button>
      </div>
    </div>

    <base-tree
      v-model="treeData"
      :loadData="loadData"
      :editable="false"
      @on-select-node="selectTreeNode"
      style="height: calc(100% - 32px)"
      ref="baseTreeRef"
    ></base-tree>
  </div>
</template>

<script>
import axios from 'axios';
import cookie from 'js-cookie';
import { customAlphabet } from 'nanoid';
import localforage from 'localforage';
import tarball from '../base/tarball';
import { checkAndLoadFolderList, initFileNode, initFolderNode } from '../base/mateLocalUtil';
import BaseTree from '../components/BaseTree.vue';

const nanoid = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 16);

export default {
  components: { BaseTree },
  name: 'TreeRemote',
  data() {
    return {
      access_token: '123.27e3984b7d4b75c86ed75e84f85ae1df.YQHw5oyKhUDaMlIb09uMnK2fSqKNDA3NLjFCmFx.LKo6aA',

      treeData: [
        {
          title: '服务端存储',
          path: '/_mateRoot',
          loading: false,
          expand: true,
          selected: true,
          nodeIcon: 'md-filing',
          nodeType: 'root',
          nodeId: 'root',
          children: [],
        },
      ],
      curNode: null,

      rootInfo: {
        avatar_url:
          'https://dss0.bdstatic.com/7Ls0a8Sm1A5BphGlnYG/sys/portrait/item/netdisk.1.c4ac2db1.kuUWVJHIT157XG_Rh2znUw.jpg',
        baidu_name: 'irsv67',
        errmsg: 'succ',
        errno: 0,
        netdisk_name: '',
        request_id: '225190628193509553',
        uk: 1225107180,
        vip_type: 0,
      },

      usedInfo: {
        errno: 0,
        total: 2208686931968,
        free: 2208686931968,
        request_id: 226231296015707780,
        expire: false,
        used: 785290869659,
      },

      fileProcess: 0,
    };
  },
  props: {
    aaa: {
      type: String,
    },
    bbb: {
      type: Object,
    },
  },
  methods: {
    async pullFolder() {
      const aaa =
        'PSTM=1658909059; BIDUPSID=EE911EF24F666265E28F5A6CE8346C12; ZFY=1Lxv5K6x0n74W1wIUAA0lsRJoyX1fQWIY1ZjEy:AeAho:C; BAIDUID=490A1F7BB1FAC201598C19FA00976713:SL=0:NR=10:FG=1; BAIDUID_BFESS=6FFF3F723C31B1D299EC71EE8AFB67F2:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; STOKEN=b5723f6cf13d7c5ae87e71df062700eebd0b406ba4d5ff59dc8f318305de9e4c; pcsett=1659145680-0eb50c99bed1bfe32e7d6544d2f319d8; ab_sr=1.0.1_ZTliNzU0NGEyNDU3NGM5MDRjYWFhNGY3ZDU1NWIxOWZmMTljZGY3ZWY5MjRjMmI5NzI2MTkzYjQ3MWE0ZjZjNDcwZmNmZWQwYzVkNDI5MDM4ZGZkNmM3NThlM2UzMGM3NjRiMmQ1ODIyMjcwZTFhYTU5YjE5ZjE4NTRhNGI0OTcxMTJmMGU0ZTc4ODYwMjAwOTAxNDc3NTljZDVlM2RmMw==; BDUSS=pidzZMeGdBU0tCcU1Mbm5mUXppRH5-a3FQekdSYVphTDdIRjd3SzFmOEJ6UXBqSVFBQUFBJCQAAAAAAAAAAAEAAADoSTMBaXJzdjY3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFA42IBQONiUX; BDUSS_BFESS=pidzZMeGdBU0tCcU1Mbm5mUXppRH5-a3FQekdSYVphTDdIRjd3SzFmOEJ6UXBqSVFBQUFBJCQAAAAAAAAAAAEAAADoSTMBaXJzdjY3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFA42IBQONiUX';
      const itemList = aaa.split('; ');
      itemList.forEach(item => {
        const array = item.split('=');
        cookie.set(array[0], array[1], { expires: 7 });
      });

      // 获取文件信息
      const fsids = this.curNode.children.map(item => item.fs_id).join(',');
      const url = `/rest/2.0/xpan/multimedia?method=filemetas&access_token=${this.access_token}&fsids=[${fsids}]&thumb=1&dlink=1&extra=1`;
      const infoList = await axios.get(url).then(retObj => {
        return retObj.data.list;
      });

      // 获取文件实体
      const _this = this;
      const reqList = infoList.map(item => {
        const newLink = '/file' + item.dlink.split('/file')[1];
        // console.log(item.dlink);
        return axios.get(newLink, {
          responseType: 'blob',
          onDownloadProgress: function (progressEvent) {
            // todo 精确进度条
            // console.log(progressEvent.loaded + ' / ' + progressEvent.total);
            _this.fileProcess += 10;
            _this.$Loading.update(_this.fileProcess);
          },
        });
      });

      this.fileProcess = 0;
      this.$Loading.config({
        color: '#19be6b',
      });
      this.$Loading.start();
      const retList = await Promise.all(reqList);
      this.$Loading.finish();
      this.$Message.success('下载完成');

      // 定位本地文件夹
      const localRoot = await checkAndLoadFolderList();
      let curFolder = localRoot[0].children.find(item => {
        return item.title === this.curNode.title;
      });
      if (!curFolder) {
        curFolder = initFolderNode(this.curNode.title);
        localRoot[0].children.push(curFolder);
      }

      // todo 完善Promise逻辑
      retList.forEach((tmpObj, i) => {
        const fileName = infoList[i].filename;
        const curFile = new File([tmpObj.data], fileName);
        const fileNode = initFileNode(curFile, this.curNode.nodeId);
        localforage.setItem(fileNode.fileKey, curFile).then(() => {
          curFolder.children.push(fileNode);
          localforage.setItem('_folderList', localRoot);
        });
      });
    },
    formatSize(param) {
      const tmpNum = param / (1024 * 1024 * 1024);
      return tmpNum.toFixed(0);
    },
    exportFile() {
      if (this.curNode.nodeType !== 'file') {
        return;
      }
      localforage.getItem(this.curNode.fileKey).then(fileObj => {
        let linkEle = document.createElement('a');
        linkEle.href = URL.createObjectURL(fileObj);
        linkEle.download = fileObj.name;
        document.body.appendChild(linkEle);
        linkEle.click();
        document.body.removeChild(linkEle);
      });
    },
    exportFolder() {
      if (this.curNode.nodeType !== 'folder') {
        return;
      }
      const fileInfoList = this.curNode.children.map(fileNode => {
        return localforage.getItem(fileNode.fileKey);
      });
      Promise.all(fileInfoList).then(fileList => {
        let tar = new tarball.TarWriter();
        fileList.forEach(contentObj => {
          tar.addFile(contentObj.name, contentObj);
        });
        tar.download(this.curNode.title + '.tar');
      });
    },

    selectTreeNode(curNode) {
      this.curNode = curNode;

      if (this.curNode.nodeType === 'folder' && this.curNode.children.length === 0) {
        const loadNode = this.curNode;

        loadNode.loading = true;
        this.getFolderList(loadNode).then(retObj => {
          loadNode.loading = false;
          loadNode.children = retObj;
          this.$emit('select-tree-node', loadNode);
        });
      } else {
        this.$emit('select-tree-node', this.curNode);
      }
    },

    async getUserInfo() {
      // 获取用户信息
      const url = '/rest/2.0/xpan/nas?method=uinfo&access_token=' + this.access_token;
      this.rootInfo = await axios.get(url).then(retObj => {
        return retObj.data;
      });

      // 获取用量信息
      // const url2 = '/api/quota?access_token=' + this.access_token + '&checkfree=1&checkexpire=1';
      // this.usedInfo = await axios.get(url2).then(retObj => {
      //   return retObj.data;
      // });
    },

    async getFolderList(pNode) {
      // 获取目录
      const url3 = `/rest/2.0/xpan/file?method=list&dir=${pNode.path}&folder=0&access_token=${this.access_token}`;
      const srcList = await axios.get(url3).then(retObj => {
        return retObj.data.list;
      });

      const folderList = srcList.map(item => {
        const folderName = item.server_filename;
        const tmpId = nanoid();
        const nodeType = item.isdir ? 'folder' : 'file';
        const nodeIcon = item.isdir ? 'md-folder' : 'ios-document-outline';
        const loading = item.isdir ? false : undefined;
        const retObj = {
          title: folderName,
          path: item.path,
          fs_id: item.fs_id,
          nodeIcon: nodeIcon,
          nodeType: nodeType,
          nodeId: tmpId,
          parentId: pNode.nodeId,
          fileInfo: {
            name: folderName,
            type: nodeType,
            size: item.size,
            lastModified: item.server_mtime * 1000,
          },
          children: [],
        };
        if (item.isdir) {
          retObj.loading = false;
        }
        return retObj;
      });

      // pNode.children = folderList;
      return folderList;
    },
    loadData(item, callback) {
      this.getFolderList(item).then(retObj => {
        callback(retObj);
        // this.$emit('select-tree-node', item);
        this.$refs.baseTreeRef.handleSelect(item.nodeKey);
      });
    },
  },
  mounted() {
    this.getUserInfo().then(() => {
      const loadNode = this.treeData[0];

      loadNode.loading = true;
      this.getFolderList(loadNode).then(retObj => {
        loadNode.loading = false;
        loadNode.children = retObj;
        this.$emit('select-tree-node', loadNode);
      });
    });
  },
};
</script>

<style scoped>
.tree-bar {
  display: flex;
  height: 32px;
  line-height: 36px;
  background-color: #ffffff;
  padding: 0 16px;
}

.top-btn {
  /* width: 40px; */
  margin-right: 4px;
}
</style>
